import { Injectable } from '@nestjs/common';
import Redis from 'ioredis';
import { InjectRedis } from '~/common/decorators/inject-redis.decorator';
import { genCaptchaImgKey } from '~/helper/genRedisKey';
import { isEmpty } from 'lodash';
import { BusinessException } from '~/common/exceptions/biz.exception';
import { ErrorEnum } from '~/constants/error-code.constant';

@Injectable()
export class CaptchaService {
  constructor(@InjectRedis() private redis: Redis) {}

  // 校验图片验证码
  async checkImgCaptcha(id: string, code: string) {
    const result = await this.redis.get(genCaptchaImgKey(id));
    if (isEmpty(result) || code.toLowerCase() !== result.toLowerCase())
      throw new BusinessException(ErrorEnum.INVALID_VERIFICATION_CODE);

    // 校验成功后移除验证码
    await this.redis.del(genCaptchaImgKey(id));
  }
}
